from rest_framework import serializers
from .models import OauthQQUser,OauthSinaUser
from users.models import User
from .utils import check_safe_token
from django_redis import get_redis_connection

class OauthQQUsersSerializer(serializers.Serializer):

    mobile = serializers.RegexField(regex=r'1[345789]\d{9}',label='手机号')
    password = serializers.CharField(max_length=20,min_length=8,label='密码')
    sms_code = serializers.CharField(max_length=6,min_length=6,label='短信验证码')
    access_token = serializers.CharField(label='第三方账户认证ID')

    def validate(self, attrs):

        #1.先验证access_token是否正确，并拿到openid
        openid = check_safe_token(attrs['access_token'])
        if openid is None:
            raise serializers.ValidationError('access_token无效')

        #2.验证验证码是否正确
        redis = get_redis_connection('code')
        try:
            sms_redis = redis.get('sms_%s'%attrs['mobile'])
        except Exception:
            raise serializers.ValidationError('读取服务器数据失败')

        if sms_redis.decode() != attrs['sms_code']:
            raise serializers.ValidationError('验证码错误')

        #3.检查用户是否存在
        user = None
        try:
            user = User.objects.get(mobile = attrs['mobile'])
        except User.DoesNotExist:
            #3.1如果不存在，创建账户
            user = None
            pass
        else:
            #3.2如果存在，检查密码

            if not user.check_password(attrs['password']):
                raise serializers.ValidationError('用户名或密码错误')


        attrs['user'] =user
        attrs['openid'] = openid

        return attrs

    def create(self, validated_data):

        user = validated_data.get('user')

        if not user:
            user = User.objects.create(
                username = validated_data.get('mobile'),
                mobile = validated_data.get('mobile'),
                password = validated_data.get('password')
            )
            user.set_password(validated_data.get('password'))
            user.save()

        OauthQQUser.objects.create(
            openid = validated_data.get('openid'),
            user = user
        )

        return user




class OauthSinaUsersSerializer(serializers.Serializer):

    mobile = serializers.RegexField(regex=r'1[345789]\d{9}', label='手机号')
    password = serializers.CharField(max_length=20, min_length=8, label='密码')
    sms_code = serializers.CharField(max_length=6, min_length=6, label='短信验证码')
    access_token = serializers.CharField(label='第三方账户认证ID')

    def validate(self, attrs):

        # 1.先验证access_token是否正确
        access_token = check_safe_token(attrs['access_token'])
        if access_token is None:
            raise serializers.ValidationError('access_token无效')

        # 2.验证验证码是否正确
        redis = get_redis_connection('code')
        try:
            sms_redis = redis.get('sms_%s' % attrs['mobile'])
        except Exception:
            raise serializers.ValidationError('读取服务器数据失败')

        if sms_redis.decode() != attrs['sms_code']:
            raise serializers.ValidationError('验证码错误')

        # 3.检查用户是否存在
        user = None
        try:
            user = User.objects.get(mobile=attrs['mobile'])
        except User.DoesNotExist:
            # 3.1如果不存在，创建账户
            user = None
            pass
        else:
            # 3.2如果存在，检查密码

            if not user.check_password(attrs['password']):
                raise serializers.ValidationError('用户名或密码错误')

        attrs['user'] = user
        attrs['access_token'] = access_token

        return attrs

    def create(self, validated_data):

        user = validated_data.get('user')

        if not user:
            user = User.objects.create(
                username=validated_data.get('mobile'),
                mobile=validated_data.get('mobile'),
                password=validated_data.get('password')
            )
            user.set_password(validated_data.get('password'))
            user.save()

        OauthSinaUser.objects.create(
            access_token=validated_data.get('access_token'),
            user=user
        )

        return user










